var express = require('express');
var router = express.Router();
const bcrypt = require("bcrypt");
const { TOKEN_KEY } = require('../utils/const');
const jwt = require("jsonwebtoken");

const { AdminsLogin, SuperAdminsLogin2, AddAdmins, getAdmins, setAdmins,getData,getData2,getData3 } = require('../service/adminsService');

//管理员登录
router.post('/login', async function (req, res, next) {
  var { username, password } = req.body;
  const data = await AdminsLogin({ username })
  if(data.length==0){
    res.send({
        status: 0,
        message: "登录失败"
    })
  }
  if (bcrypt.compareSync(password, data[0].password)) {
    const token = jwt.sign(
      { username },
      TOKEN_KEY,
      { expiresIn: 6000 }
    )
    if(data[0].state==2){
        res.send({
            status: 0,
            message: "登录失败,该账号已被冻结"
        })
    }
    res.send({
      ...data,
      token,
      status: 1
    })
  } else {
    res.send({
      status: 0,
      message: "登录失败"
    })
  }
})

//超级管理员登录
router.post('/superAdminsLogin', async (req, res, next) => {
  const msg = req.body;
  const data = await SuperAdminsLogin2(msg);
  if(data.data.length==0){
    res.send({ message: '登录失败', status: 0 })
  }
  const {username}=data.data[0]
  if (data.status) {
    const token = jwt.sign(
      { username },//保存的用户信息
      TOKEN_KEY,//密钥字符串
      { expiresIn: 6000 }//设置token有效期，单位s 
    )
    res.send({ message: '登录成功', status: 1, token, ...data })
  } else {
    res.send({ message: '登录失败', status: 0 })
  }
});

//登录验证
router.get('/isLogin', async function (req, res, next) {
  const token = req.query;
  const { username } = jwt.verify(token[0], TOKEN_KEY);
  res.send({
    status: 1,
    message: '成功',
    username
  })
});

//新增管理员
router.post('/addAdmins', async (req, res, next) => {
  let { username, password,state,power } = req.body;
  password = bcrypt.hashSync(password, 10)
  const data = await AddAdmins({ username, password,state,power })
  res.send(data)
})

//获取管理员
router.post('/getAdmins', async (req, res, next) => {
  const msg = req.body;
  const data = await getAdmins(msg);
  res.send(data)
})
//修改管理员信息
router.post('/setAdmins', async (req, res, next) => {
  const msg = req.body;
  msg.password = bcrypt.hashSync(msg.password, 10)
  const data = await setAdmins(msg);
  res.send(data)
})

router.get('/getData',async(req,res,next)=>{;
    const data = await getData();
    res.send(data)
})

router.get('/getData2',async function(req,res,next){
    const data = await getData2();
    res.send(data)
})
router.get('/getData3',async function(req,res,next){
    const data = await getData3();
    res.send(data)
})

module.exports = router
